package com.ff.neuropp.service;


import com.ff.neuropp.domain.SystemLog;
import com.ff.neuropp.repository.SystemLogRepository;
import com.ff.neuropp.util.SpecificationUtil;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class SystemLogService {

    @Resource
    private SystemLogRepository systemLogRepository;


    public List<SystemLog> searchSystemLogsByTag(String beginTime, String endTime, String logAccount) {
        return systemLogRepository.findAll(new Specification<SystemLog>() {
            @Override
            public Predicate toPredicate(Root<SystemLog> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (null != beginTime && beginTime.length()>0) {
                    list.add(criteriaBuilder.greaterThan(root.get("create_date").as(String.class),  beginTime));
                }
                if (null != endTime && endTime.length()>0) {
                    list.add(criteriaBuilder.lessThan(root.get("create_date").as(String.class), endTime ));
                }
                if (null != logAccount && logAccount.length()>0) {
                    list.add(criteriaBuilder.like(root.get("logAccount").as(String.class), "%" + logAccount + "%"));
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        });
    }


    public void save(SystemLog systemLog) {
        systemLogRepository.save(systemLog);
    }

    /**
     * 根据条件查询List
     */
    public List<SystemLog> findList(Map<String, Object> param) {
        return systemLogRepository.findAll(SpecificationUtil.buildSpecificationSort(param, SystemLog.class));
    }
}
